//
//  FindViewController.m
//  NuwaRobot
//
//  Created by Kendama on 2017/12/5.
//  Copyright © 2017年 Kendama. All rights reserved.
//

#import "FindViewController.h"
#import "CYTabBarViewController.h"
#import "CYTabBar.h"
#import "CollectionViewController.h"
#import "XMSDK.h"
#import "XMCategory.h"
#import "BindDeviceView.h"
#import "ScanDeviceViewController.h"
#import "GetUserDeviceApi.h"

@interface FindViewController ()

@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic,strong)NSArray *orderData;
@property(nonatomic,strong) BindDeviceView *bindDeviceView;

@end

@implementation FindViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self getUserDevice];
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)refreshBaseControlValue
{
    [self updateCategoriesList];
}

#pragma mark --- 点击事件
- (void)didClickScanDeviceButton
{
    ScanDeviceViewController *vc = [ScanDeviceViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark 数据刷新
- (void)getUserDevice
{
    if ([EXRACT_OBJECT(DEVICEID) isEqualToString:@"0"] || !EXRACT_OBJECT(DEVICEID)) // 没有设备
    {
        GetUserDeviceApi *api = [[GetUserDeviceApi alloc] init];
        [api dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
            NSDictionary *dict = request.responseJSONObject[@"data"];
            NSString *deviceID = dict[@"device_id"];
            if ([deviceID intValue] == 0) // 没有绑定设备
            {
                self.bindDeviceView.hidden = NO;
            }
            else
            {
                self.bindDeviceView.hidden = YES;
            }
            SAVE_OBJECT(deviceID, DEVICEID);
            SAVE_OBJECT(dict[@"sn"], DEVICEMAC);
        } failure:nil];
    }
    else
    {
        self.bindDeviceView.hidden = YES;
    }
    
}

// 获取分类数据
- (void)updateCategoriesList
{
    [SVProgressHUD showWithStatus:@"正在获取中..."];
//    [SVProgressHUD showInfoWithStatus:@"正在获取中..."];
    [[XMReqMgr sharedInstance] requestXMData:XMReqType_CategoriesList params:nil withCompletionHander:^(id result, XMErrorModel *error) {
        if (!error)
        {
            [self.dataSource removeAllObjects];
            for (NSString *string in self.orderData)
            {
                for (NSDictionary *dict in result)
                {
                    if ([string isEqualToString:dict[@"category_name"]])
                    {
                        XMCategory *model = [[XMCategory alloc] initWithDictionary:dict];
                        [self.dataSource addObject:model];
                    }
//                    NSLog(@"%@和%@",dict[@"category_name"],dict[@"id"]);
                }
            }
            [self initTabbar];
        }
        else
        {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self updateCategoriesList];
            });
            [SVProgressHUD showErrorWithStatus:error.error_desc];
        }
    }];
}

// 初始化顶部菜单栏
- (void)initTabbar
{
    NSMutableArray *vcArray = [NSMutableArray arrayWithCapacity:11];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // 使用和tabBarController一致  这里就不在写用法了
    CYTabBarViewController *tabBarVC = [[CYTabBarViewController alloc] initWithTopStyle:CYTopTitleViewStyleBaseLine];
    [tabBarVC cy_showInViewController:self];
    
    for (XMCategory *model in self.dataSource)
    {
        CollectionViewController *vc = [CollectionViewController new];
        vc.categoryModel = model;
        vc.cy_tabBarItem.cy_titleN = model.categoryName;
        vc.view.backgroundColor = [UIColor grayColor];
        [vcArray addObject:vc];
    }
    
    // 设置正常文本的颜色
    tabBarVC.titleView.cy_titleNormalColor = [UIColor grayColor];
    
    // 设置选中文本颜色
    tabBarVC.titleView.cy_titleSelectedColor = rgba(0,159,236,1);
    
    tabBarVC.titleView.cy_lineColor = rgba(0,159,236,1);
    
    // 设置字体大小
    tabBarVC.titleView.cy_titleFont = fontCommonSize;
    
    // 设置当前选中
    tabBarVC.cy_selectedIndex = 0;
    
    // 设置所有数据
    tabBarVC.cy_viewControllers = vcArray;
    
    [self.view bringSubviewToFront:self.navigationBar];
    
    [SVProgressHUD dismiss];

}

- (NSMutableArray *)dataSource
{
    if(!_dataSource)
    {
        _dataSource = [[NSMutableArray alloc]init];
    }
    return _dataSource;
}

- (NSArray *)orderData
{
    if(!_orderData)
    {
        _orderData = @[@"有声书",@"相声评书",@"音乐",@"历史",@"情感生活",@"脱口秀",@"娱乐",@"健康养生",@"广播剧",@"戏曲",@"电台",@"商业财经"];
    }
    return _orderData;
}

- (BindDeviceView *)bindDeviceView
{
    if(!_bindDeviceView)
    {
        UIView *superView = self.view;
        _bindDeviceView = [[BindDeviceView alloc]init];
        [superView addSubview:_bindDeviceView];
        [_bindDeviceView.scanButton addTarget:self action:@selector(didClickScanDeviceButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _bindDeviceView;
}

#pragma mark --- 设置视图布局
- (void)masLayoutSubview
{
    __weak UIView *superView = self.view;
    
    [self.bindDeviceView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(64);
        make.left.right.bottom.mas_equalTo(superView);
    }];
    
}

- (void)setNavigationStyle
{
    [self setNavigationBarTitle:@"发现"];
    [self setLeftButtonImage:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
